<?php


namespace app\controller\api\member;
use app\FrontendController;
use app\model\frontend\SettingModel;

use app\model\frontend\CustomerModel;
use app\model\frontend\CouponModel;
use app\model\tool\ImageModel;
use think\facade\Filesystem;
use think\facade\Request;

use wxaes\WXBizDataCrypt;
use wxaes\ErrorCode;
use EasyWeChat\MiniApp\Application;

class Xcx extends FrontendController{


    private $customer_bg_img_default = '/storage/assets/image/user-cover.png';
    public function login(){

        global $_GPC;
        global $_W;
        $json = [
            "status"=>0
        ];
        if( empty($_GET['code']) ){

            $json['status'] = 1;
            $json['description'] = '参数不合法';
            echo json_encode( $json );
            die();

        }

        $xcx_setting = SettingModel::get_xcx();
        if( !empty( $xcx_setting['app_id'] ) || !empty( $xcx_setting['app_secret'] ) ){
            $appId = $xcx_setting['app_id'];
            $appSecret = $xcx_setting['app_secret'];
        }else {
            $appId = $_W['account']['key']??'';
            $appSecret = $_W['account']['secret']??'';
        }

        //todo 获取 后台设置中的小程序 appID, appSecret
//        $appId = 'wx85aca1163a609063';
//        $appSecret = '2d28d18418f438a3c3bfac0f7a526244';


        $code = $_GPC['code'];
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='. $appId . '&secret='. $appSecret . '&js_code=' .  $code . '&grant_type=authorization_code';

        $res = $this->request_remote( $url );
        $res['shop_name'] = !empty($xcx_setting['shop_name'])?$xcx_setting['shop_name']:'神秘商城';
        $res['location_key'] = !empty($xcx_setting['location_key'])?$xcx_setting['location_key']:'';

        $config_setting = settingModel::get_config();
        $res['shop_phone']      = !empty($config_setting['phone'])          ? $config_setting['phone']          : '';
        $res['shop_wechat']     = !empty($config_setting['wechat'])         ? $config_setting['wechat']         : '';
        $res['shop_qq']         = !empty($config_setting['qq'])             ? $config_setting['qq']             : '';
        $res['float_nav_show']  = !empty($xcx_setting['float_nav_show'])    ? $xcx_setting['float_nav_show']    : 0;

        // todo 获取用户中心背景图片
        $customer_bg_img = settingModel::get('customer_center','bg_img');
        $this->customer_bg_img_default = $this->url_host . $this->customer_bg_img_default;
        $res['customer_bg_img'] = $customer_bg_img ? ImageModel::resize2($customer_bg_img['value']): $this->customer_bg_img_default;
        $customer_enter_box = settingModel::get('customer_center','entry_box');
        $res['customer_entry_box'] = $customer_enter_box?$customer_enter_box['value']:0;
        $res['app_id'] = $appId;
        if( !empty($res['openid']) ){
            $_SESSION['openid'] = $res['openid'];

//            $res['customer'] = CustomerModel::getCustomerXcx( $res['openid'] );
            $res['customer'] = CustomerModel::getCustomer( $res['openid'] );
            $res['status'] = 0;
        }else{
            $res['status'] = 1;
        }

        echo json_encode( $res );
    }

    public function request_remote( $url , $data = [], $response_type = 'array' ){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        // curl_setopt($ch, CURLOPT_HEADER, 0);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        // $headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        if(!empty($data)){
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        $file = curl_exec($ch);
        curl_close($ch);

        if( $file === false ){
            $file = curl_error( $ch );
        }
        
        if( $response_type == 'array' ){
            return json_decode( $file, true );
        }else{
            return $file;
        }

    }


    public function getCustomer(){

        global $_W;
        $res = [
            'status'=>0,
            'telephone'=>'',
        ];

        if( empty( $_GET['openid']) ){

            $res['status'] = 1;
            $res['description'] = '请求不合法';
            echo json_encode( $res );
            die();

        }

        $openid = $_GET['openid'];

//        $customer_xcx = CustomerModel::getCustomerXcx( $openid );
        $customer_xcx = CustomerModel::getCustomer( $openid );

        // $res['credit'] = CustomerModel::credit(); // 积分 
        // $res['group'] = CustomerModel::group();
        // $res['coupon'] = CouponModel::getList($customer_xcx['id']);

        $customer_xcx['headUrl'] = Request::instance()->domain() . '/storage/' . $customer_xcx['headUrl'];    
//        if( !empty( $customer_xcx ) &&  !empty( $customer_xcx['telephone'] )  ){
        if( !empty( $customer_xcx )  ){
            $res['telephone'] = $customer_xcx['telephone'];
            $res['customer'] = $customer_xcx;
        }else{
            $res['status'] = 1;
            $res['description'] = '用户未注册';
        }

        echo json_encode( $res );

    }

    /**
     * 小程序注册
     */
    public function register(){

        global $_W,$_GPC;
        $res = [
            'status'=>0
        ];

        if( empty( $_GET['openid']) ){

            $res['status'] = 1;
            $res['description'] = '请求不合法';
            echo json_encode( $res );
            die();

        }

        $openid = $_GET['openid'];
//        $uniacid = $_GET['i'];


        $xcx_setting = SettingModel::get_xcx();
        if( !empty( $xcx_setting['app_id'] ) ){
            $appId = $xcx_setting['app_id'];
        }else{
            $appId = $_W['account']['key'];
        }

        // if( $_GPC['__input'] ){
        //     $post = $_GPC['__input'];
        // }else{
            $post = $_GPC;
        // }

        // return json( $post );
        $sessionKey = $post['session_key'];
        $encryptedData = $post['encryptedData'];
        $iv = $post['iv'];
        $referee = !empty( $post['referee'] ) ? intval($post['referee']) : 0;
        // $userInfo = !empty($post['userInfo'])? json_decode( $post['userInfo'], true) :[];
        $userInfo = !empty($post['userInfo'])? ( is_array($post['userInfo']) ? $post['userInfo'] : json_decode( $post['userInfo'], true) ) :[];

        $pc = new WXBizDataCrypt($appId, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );

        if ($errCode == 0) {
            $res['data'] = json_decode($data, true);

            //todo 手机号 存储到数据库，
            if( !empty( $res['data']['phoneNumber'] ) ){

                $res['customer_id'] = CustomerModel::registerByXcx( $openid, $res['data']['phoneNumber'], $referee, $userInfo );
                if( empty( $res['customer_id'] ) ){
                    $res['status'] =  1;
                    $res['description'] = '注册失败';
                }
            }else{
                $res['status'] =  1;
                $res['description'] = '手机号获取失败';

            }

        } else {
            $res['status'] =  $errCode;
        }


        echo json_encode( $res );


    }

    //todo 获取用户的推广二维码
    public function myQrcode(){

        global $_W;
        $res = [
            'status'=>0,
        ];
        $customer_id = $_W['customer']['id'];
        $customerQrcode = CustomerModel::getCustomerQrcode( $customer_id );

        if( !empty($customerQrcode) ){

            $customerQrcode['qrcode'] = ImageModel::resize2( $customerQrcode['qrcode_path'] );
            $res['data'] = $customerQrcode;
            echo json_encode( $res );
            return;

        }else{

//            $scene_params = 'customer_id=' . $customer_id . '&uniacid=' . $_W['uniacid'];
            $scene_params = 'referee=' . $customer_id . '&uniacid=' . $_W['uniacid'];

            $account_api = \WeAccount::create();

            $response = $account_api->getCodeUnlimit($scene_params, '', 430, array(
                'auto_color' => false,
                'line_color' => array(
                    'r' => '#ABABAB',
                    'g' => '#ABABAC',
                    'b' => '#ABABAD',
                ),
            ));

            if( is_error( $response )){
                $res['status'] = 1;
//                $res['description'] = '二维码生成失败';
                $res['description'] = isset($response['message'])?$response['message']: '二维码生成失败';
                echo json_encode( $res );
                die();
            }

            load()->func('file');

            $qrcode_path =  'qrcode/' . $_W['uniacid'];
            $qrcode_path .= '/customer_' . $customer_id . '.png' ;
            $ret = file_write(  $qrcode_path, $response );
            

            //todo 保存数据库
            $data = [
                'customer_id'   => $customer_id,
                'scene'         => $scene_params,
                'qrcode_path'   => $qrcode_path,
            ];

            $res['ret'] = CustomerModel::setCustomerQrcode( $data );

            if( $res['ret'] ){
                $data['qrcode'] = ImageModel::resize2( $data['qrcode_path'] );
                $res['data'] = $data;
            }else{
                $res['status'] = 1;
                $res['description'] = '二维码保存失败';
            }


            echo json_encode( $res );
        }



    }

    //todo 获取用户的推广二维码 （独立版，从上面的myQrcode方法拷贝下来， 再修改）
    /**
     * 废弃， easywechat6 调试不成功
     */
    public function myQrcode2(){

        global $_W;
        $res = [
            'status'=>0,
        ];
        $customer_id = $_W['customer']['id'];
        $customerQrcode = CustomerModel::getCustomerQrcode( $customer_id );

        if( !empty($customerQrcode) ){

            $customerQrcode['qrcode'] = ImageModel::resize2( $customerQrcode['qrcode_path'] );
            $res['data'] = $customerQrcode;
            echo json_encode( $res );
            return;

        }else{

            
            $wechatApp = $this->createWechatApp(  );
            
            $scene_params = 'referee=' . $customer_id . '&uniacid=' . $_W['uniacid'];

            try{
                $response = $wechatApp->getClient()->postJson('/wxa/getwxacodeunlimit', [
                    'scene' => $scene_params,
                    // 'page' => 'sm_shop/pages/home/home',
                    'page' => '',
                    'width' => 430,
                    'check_path' => false,
                    'auto_color' => false,
                    'line_color' => array(
                        'r' => '#ABABAB',
                        'g' => '#ABABAC',
                        'b' => '#ABABAD',
                    ),
                ])->toStream();

                $path_pre = public_path() . '/storage/';
                $qrcode_path =  'qrcode/' . $_W['uniacid'];
                $qrcode_path .= '/customer_' . $customer_id . '.png' ;

                $path = $response->saveAs( $path_pre . $qrcode_path );
                return json( $path );
                //todo 保存数据库
                $data = [
                    'customer_id'   => $customer_id,
                    'scene'         => $scene_params,
                    'qrcode_path'   => $qrcode_path,
                ];
    
                $res['ret'] = CustomerModel::setCustomerQrcode( $data );
    
                if( $res['ret'] ){
                    $data['qrcode'] = ImageModel::resize2( $data['qrcode_path'] );
                    $res['data'] = $data;
                }else{
                    $res['status'] = 1;
                    $res['description'] = '二维码保存失败';
                }

                echo json_encode( $res );

            }catch( \Throwable $e ){
                // 失败
                $message =  $e->getMessage();
                $res['status'] = 1;
                $res['description'] = isset( $message ) ? $message : '二维码生成失败';
                echo json_encode( $res );
                die();
            }

            
        }



    }

    //todo 获取用户的推广二维码 （独立版，从上面的myQrcode方法拷贝下来， 再修改）
    /**
     * 已走通， 还需要完善
     */
    public function myQrcode3(){

        global $_W;
        $res = [
            'status'=>0,
        ];
        $customer_id = $_W['customer']['id'];
        $customerQrcode = CustomerModel::getCustomerQrcode( $customer_id );

        if( !empty($customerQrcode) ){

            $customerQrcode['qrcode'] = ImageModel::resize2( $customerQrcode['qrcode_path'] );
            $res['data'] = $customerQrcode;
            echo json_encode( $res );
            return;

        }else{

            $scene_params = 'referee=' . $customer_id . '&uniacid=' . $_W['uniacid'];

            $params = [
                'scene' => $scene_params,
                'page' => '',
                'check_path' => false,
                'env_version' => 'release',
                'width' => 430,
                'auto_color' => false,
                'line_color' => [
                    'r' => '#ABABAB',
                    'g' => '#ABABAC',
                    'b' => '#ABABAD',
                ],
                'is_hyaline' => false,
            ];
            $response_buffer = $this->getQRCode( $params );

            $path_pre = public_path() . '/storage/';
            $qrcode_path =  'qrcode/' . $_W['uniacid'];
            $qrcode_path .= '/customer_' . $customer_id . '.png' ;

            $ret = file_put_contents( $path_pre . $qrcode_path, $response_buffer );

            if( $ret ){
                //todo 保存数据库
                $data = [
                    'customer_id'   => $customer_id,
                    'scene'         => $scene_params,
                    'qrcode_path'   => $qrcode_path,
                ];
                $res['ret'] = CustomerModel::setCustomerQrcode( $data );

                $data['qrcode'] = ImageModel::resize2( $data['qrcode_path'] );
                $res['data'] = $data;
            }else{
                $res['status'] = 1;
                $res['description'] = '二维码保存失败';
            }

            echo json_encode( $res );

            

            
        }



    }

    private function createWechatApp(){
        // mb_internal_encoding("UTF-8");
        $config = [
            'app_id' => 'wxd689b76dabb1077a',
            'secret' => 'c00ebe041e037ea9c45745738378c591',
            // 'token' => 'xWFA57z9ZlYARrQ9fVmMrw5PrRL9AM3L',
            // 'aes_key' => 'IHlhqoO6XH6cd9lZHxXkF6lp0E7lpcOxdhZxo7oeMXh',
        ];
        $app = new Application($config);
        return $app;
    }

    /**
     * 获取小程序 access_token
     */
    private function getAccessToken(){

        
        $url = 'https://api.weixin.qq.com/cgi-bin/token';

        $params = [
            'grant_type'    => 'client_credential',
            'appid'         => 'wxd689b76dabb1077a',
            'secret'        => 'c00ebe041e037ea9c45745738378c591',
        ];

        $result = array_map(function($key, $value) {
            return $key . '=' . $value;
        }, array_keys($params), $params);

        $params_str = implode('&', $result );
        $url .= '?' . $params_str;

        $res = $this->request_remote( $url );

        
        return $res;
    }

    /**
     * 
     */
    private function getQRCode( $params ){

        $res = $this->getAccessToken();

        $access_token = $res['access_token'];
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;
        
        $params = json_encode( $params );
        // echo  $params;
        $qrcode_buffer = $this->request_remote( $url, $params, 'string' );

        return $qrcode_buffer;
    }

    public function uploadAvatar(){   

        global $_W;
        $uniacid = $_W['uniacid'];
        $file = request()->file('file');
        // 上传到本地服务器
        $uniacid = $_GET['i'];
        
        $savename = Filesystem::disk('public')->putFile( '/avatar/' . $uniacid , $file);
        // return $savename ; // 不加 json 函数过滤 会有调试信息！！！ 
        return json( $savename ); 

    }

}